package com.onekbase.demo.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpGatewayBioThreadPoolDemo {
    public static void main(String[] args) {
        try {
            int port = 8083;
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("Server started on port "+port);
            ExecutorService executorService = Executors.newFixedThreadPool(60);
            while (true) {
                Socket clientSocket = serverSocket.accept();
                executorService.submit(() -> {
                    try ( InputStream inputStream = clientSocket.getInputStream();
                          OutputStream outputStream = clientSocket.getOutputStream();){
                        byte[] buffer = new byte[1024];
                        int bytesRead = inputStream.read(buffer);
                        String clientData = new String(buffer, 0, bytesRead);
                        System.out.println("Received from client: " + clientData);
                        String response = TcpGatewayUtils.request(clientData, "localhost", 8084);
                        outputStream.write(response.getBytes());
                        outputStream.flush();
                    } catch (Exception e){
                        e.printStackTrace();
                    }finally {
                        try {
                            clientSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}